"""该模块为为selenium方法实现对网页的操作"""
import os
from selenium import webdriver
import yaml
from typing import Optional
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from log_Action import LogModel

wr = LogModel().get_log()


class SeDriver(object):
    def __init__(self, chrome: Optional[str] = '../Charom_driver/chromedriver.exe', url: Optional[str] = "https://www.adidas.com.cn/") -> None:
        try:
            wr.info("开始获取驱动地址：地址为:%s" % chrome)
            self.option = webdriver.ChromeOptions()
            self.option.add_experimental_option("detach", True)
            self.driver = webdriver.Chrome(executable_path=chrome, options=self.option)
            self.timeout = 10
            self.wait = WebDriverWait(self.driver, self.timeout)
        except TypeError:
            wr.error("驱动地址不正确")
            raise "检测chrome的驱动地址是否正确"
        self.url = url

    def login_url(self):
        '''
        :仅打开网页，不做任何执行操作，以driver为主
        :return:
        '''
        wr.info("开始登录网址：%s" % self.url)
        self.driver.implicitly_wait(10)
        self.driver.get(self.url)

    def getByLocal(self, ways: Optional[str], key: Optional[str]):
        if ways == 'name':
            return By.NAME, key
        elif ways == 'id':
            return By.ID, key
        elif ways == 'xpath':
            return By.XPATH, key
        elif ways == 'link_text':
            return By.LINK_TEXT, key
        elif ways == 'class_name':
            return By.CLASS_NAME, key
        else:
            print("暂未定义此定位元素方式")

    def click_send(self, ways: Optional[str], key: Optional[str]):
        """
        :param ways: 定位方式，ID/NAME/CSS
        :param key: 定位元素名
        :return:
        """
        try:
            self.wait.until(lambda driver: self.driver.find_element(*(self.getByLocal(ways, key)))).click()
        except ValueError:
            raise "查找的元素不存在"

    def send_key(self, ways: Optional[str], key: Optional[str], value: Optional[str]):
        """
        :param self:
        :param ways: 定位方式，ID/NAME/CSS
        :param key: 定位元素名
        :param value: 需要输入的值
        :return:
        """
        try:
            self.wait.until(lambda driver: self.driver.find_element(*(self.getByLocal(ways, key)))).send_keys(value)
        except ValueError:
            raise "元素不匹配"

    def _quit(self):
        self.driver.quit()

